import React, { useState, useEffect, useRef } from 'react'
import '@wangeditor/editor/dist/css/style.css'
import { Dropdown, Menu, Space, Button, message, Drawer, Form, Input, Card, Pagination, PaginationProps, Popconfirm, Upload, UploadProps, InputNumber } from 'antd';
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import {IButtonMenu, IDomEditor, IEditorConfig, IToolbarConfig, Boot} from '@wangeditor/editor'
import request from '@/utils/request';
import markdownModule from '@wangeditor/plugin-md'
import { getImgList, getInnerHtml, getImgListpage } from '@/api/newweb';
import { connect, history } from 'umi';
import "./newweb.less"
import copy from "copy-to-clipboard"
import { UploadOutlined } from '@ant-design/icons';
import moment from 'moment';
import { newActicle } from '@/utils/works';
import axios from "axios"
const { Meta } = Card;
type Props = {}

class MyButtonMenuB implements IButtonMenu {   // TS 语法
  // class MyButtonMenu {  
  title: string                     // JS 语法
  iconSvg: string
  tag: string
  constructor() {
    this.iconSvg = '<svg className="icon-wj" viewBox="0 0 1072 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3023" width="32" height="32"><path d="M491.9107146 202.62499973h209.1696427a88.39285674 88.39285674 0 0 1 88.39285675 88.39285757 32.1428573 32.1428573 0 1 0 64.28571459 0 152.67857136 152.67857136 0 0 0-152.67857134-152.67857135H491.9107146a32.1428573 32.1428573 0 1 0 0 64.28571378z m61.67410648 56.25000027L482.5491073 116.00000027a32.1428573 32.1428573 0 1 0-57.57589325 28.60714271l74.37053595 149.58482107a52.2321427 52.2321427 0 0 0 46.76785702 28.96875055H813.33928595A88.39285674 88.39285674 0 0 1 901.7321427 411.55357136v321.42857134a32.1428573 32.1428573 0 1 0 64.2857146 0V411.55357136A152.67857136 152.67857136 0 0 0 813.33928595 258.875h-259.75446487z m348.14732162 273.5357146V773.16071433a88.39285674 88.39285674 0 0 1-88.39285675 88.39285674H250.83928567A88.39285674 88.39285674 0 0 1 162.44642893 773.16071433V250.83928567A88.39285674 88.39285674 0 0 1 250.83928567 162.44642893h202.90178568a32.1428573 32.1428573 0 1 0 0-64.2857146H250.83928567A152.67857136 152.67857136 0 0 0 98.16071433 250.83928567v522.32142866A152.67857136 152.67857136 0 0 0 250.83928567 925.83928567h562.50000028a152.67857136 152.67857136 0 0 0 152.67857135-152.67857134v-240.74999973a32.1428573 32.1428573 0 1 0-64.2857146 0z" p-id="3024"></path></svg></svg>' // 可选
    this.tag = 'button'
    this.title = "打开文件"
  }
  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  getValue(editor: IDomEditor): string | boolean {   // TS 语法
    // getValue(editor) {                              // JS 语法
    return true
  }

  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(editor: IDomEditor): boolean {  // TS 语法
    // isActive(editor) {                    // JS 语法
    return false
  }

  // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
  isDisabled(editor: IDomEditor): boolean {   // TS 语法
    // isDisabled(editor) {                     // JS 语法
    return false
  }

  // 点击菜单时触发的函数
  exec(editor: IDomEditor, value: string | boolean) {
    // fileFlag = value
    if (typeof value === "string") {
      editor.insertText(value)
    }
    console.log(value, 'value')
    // console.log(fileFlag, 'editor');
  }
}
Boot.registerMenu({
  key: 'a2',
  factory() {
    return new MyButtonMenuB()
  }
})

const Newweb = (props: Props) => {
  //上传图片
  const photo: UploadProps = {
    name: 'file',
    action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null)
  const menu = (
    <Menu
      items={[
        {
          key: '1',
          label: (
            <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
              查看
            </a>
          ),
          disabled: true,
        },
        {
          key: '2',
          label: (
            <a target="_blank" rel="noopener noreferrer" onClick={() => {
              showDrawer()
            }}>
              设置
            </a>
          ),
        },
        {
          key: '3',
          label: (
            <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
              保存草稿
            </a>
          ),
        },
        {
          key: '4',
          label: (
            <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
              删除
            </a>
          ),
          disabled: true,
        },
      ]}
    />
  );

  // 编辑器内容
  // const [html, setHtml] = useState('')
  Boot.registerModule(markdownModule)
  const tocBox=useRef(null)
  const [conect, setconect] = useState({
    content:
      '\n# 欢迎使用 Wipi Markdown 编辑器\n\n> * 整理知识，学习笔记\n> * 发布日记，杂文，所见所想\n> * 撰写发布技术文稿（代码支持）\n\n## 什么是 Markdown\n\nMarkdown 是一种方便记忆、书写的纯文本标记语言，用户可以使用这些标记符号以最小的输入代价生成极富表现力的文档：譬如您正在阅读的这份文档。它使用简单的符号标记不同的标题，分割不同的段落，**粗体** 或者 *斜体* 某些文字。\n\n### 1. 待办事宜 Todo 列表\n\n- [ ] 支持以 PDF 格式导出文稿\n- [x] 新增 Todo 列表功能\n\n### 2. 高亮一段代码[^code]\n\n```python\n@requires_authorization\nclass SomeClass:\n    pass\n\nif __name__ == \'__main__\':\n    # A comment\n    print \'hello world\'\n```\n\n### 3. 绘制表格\n\n| 项目        | 价格   |  数量  |\n| --------   | -----:  | :----:  |\n| 计算机     | 1600 |   5     |\n| 手机        |   12   |   12   |\n| 管线        |    10    |  234  |\n\n### 4. 嵌入网址\n<iframe src="https://www.bilibili.com/video/BV1Ht4y1F7zS/?spm_id_from=333.337.search-card.all.click" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>\n\n```HTML\n<iframe src="https://www.bilibili.com/video/BV1Ht4y1F7zS/?spm_id_from=333.337.search-card.all.click" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>\n```\n',
    status: 'publish',
    name: '',
    path: '',
    cover: '',
    html: '<h1 id="欢迎使用-wipi-markdown-编辑器">欢迎使用 Wipi Markdown 编辑器</h1>\n<blockquote>\n  <ul>\n  <li>整理知识，学习笔记</li>\n  <li>发布日记，杂文，所见所想</li>\n  <li>撰写发布技术文稿（代码支持）</li>\n  </ul>\n</blockquote>\n<h2 id="什么是-markdown">什么是 Markdown</h2>\n<p>Markdown 是一种方便记忆、书写的纯文本标记语言，用户可以使用这些标记符号以最小的输入代价生成极富表现力的文档：譬如您正在阅读的这份文档。它使用简单的符号标记不同的标题，分割不同的段落，<strong>粗体</strong> 或者 <em>斜体</em> 某些文字。</p>\n<h3 id="1-待办事宜-todo-列表">1. 待办事宜 Todo 列表</h3>\n<ul>\n<li class="task-list-item" style="list-style-type: none;"><input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;"> 支持以 PDF 格式导出文稿</li>\n<li class="task-list-item" style="list-style-type: none;"><input type="checkbox" disabled style="margin: 0px 0.35em 0.25em -1.6em; vertical-align: middle;" checked> 新增 Todo 列表功能</li>\n</ul>\n<h3 id="2-高亮一段代码code">2. 高亮一段代码[^code]</h3>\n<pre><code class="python language-python">@requires_authorization\nclass SomeClass:\n    pass\n\nif __name__ == \'__main__\':\n    # A comment\n    print \'hello world\'\n</code></pre>\n<h3 id="3-绘制表格">3. 绘制表格</h3>\n<table>\n<thead>\n<tr>\n<th>项目</th>\n<th style="text-align:right;">价格</th>\n<th style="text-align:center;">数量</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>计算机</td>\n<td style="text-align:right;">1600</td>\n<td style="text-align:center;">5</td>\n</tr>\n<tr>\n<td>手机</td>\n<td style="text-align:right;">12</td>\n<td style="text-align:center;">12</td>\n</tr>\n<tr>\n<td>管线</td>\n<td style="text-align:right;">10</td>\n<td style="text-align:center;">234</td>\n</tr>\n</tbody>\n</table>\n<h3 id="4-嵌入网址">4. 嵌入网址</h3>\n<iframe src="https://www.bilibili.com/video/BV1Ht4y1F7zS/?spm_id_from=333.337.search-card.all.click" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>\n<pre><code class="HTML language-HTML">&lt;iframe src="https://www.bilibili.com/video/BV1Ht4y1F7zS/?spm_id_from=333.337.search-card.all.click" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"&gt; &lt;/iframe&gt;\n</code></pre>',
    toc: '[{"level":"1","id":"欢迎使用-wipi-markdown-编辑器","text":"欢迎使用 Wipi Markdown 编辑器"},{"level":"2","id":"什么是-markdown","text":"什么是 Markdown"},{"level":"3","id":"1-待办事宜-todo-列表","text":"1. 待办事宜 Todo 列表"},{"level":"3","id":"2-高亮一段代码code","text":"2. 高亮一段代码[^code]"},{"level":"3","id":"3-绘制表格","text":"3. 绘制表格"},{"level":"3","id":"4-嵌入网址","text":"4. 嵌入网址"}]',
  });
  const [low, setlow] = useState("")
  // 编辑器内容
  const [html, setHtml] = useState('')
  const toolbarConfig: Partial<IToolbarConfig> = {
    // toolbarKeys:["bold"],
    insertKeys: {
      index: 32,
      keys: "a2"
    }
  }  // TS 语法
  // console.log(editor?.getAllMenuKeys);
  // const toolbarConfig = { }                        // JS 语法
  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: '请输入内容...',
    onChange(e) {
      const  headers = e.getElemsByTypePrefix("header");
      (tocBox.current as unknown as HTMLDivElement).innerHTML=headers.map(header=>{
        const text=(header.children[0] as newActicle).text
        const {id,type}=header as newActicle
        return `<li id="${id}" type="${type}">${text}</li>`
      }).join("")
    },
  }
   //点击toc滚动
   const handleTocClick=(e:newActicle)=>{
    if(e.target.tagName==="LI"){
      editor?.scrollToElem(e.target.id);
    }
  }
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])
  const [value, setvalue] = useState("0")
  const [open, setOpen] = useState(false);
  const [value1, setvalue1] = useState("1")
  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };
  const onFinish = (values: newActicle) => {
    // console.log('Success11111:', values);
    setvalue1(values)
    // console.log(form1.getFieldsValue());
    
  };

  const onFinishFailed = (errorInfo: newActicle) => {
    // console.log('Failed:', errorInfo);
  };
  //文章属性抽屉
  const [openTwo, setOpenTwo] = useState(false);
  const showDrawerTwo = () => {
    setOpenTwo(true);
  };

  const onCloseTwo = () => {
    setOpenTwo(false);
  };

  const onFinishTwo = (values: newActicle) => {
    // console.log('Success22222:', values);
  };

  const onFinishFailedTwo = (errorInfo: newActicle) => {
    console.log('Failed:', errorInfo);
  };
  //第一个form表单绑定
  const [form1] = Form.useForm();
  //第二个form表单的绑定
  const [form] = Form.useForm();
  //图片列表
  const [imglist, setimglist] = useState([])
  //分页列表
  const [page, setpage] = useState(0)
  // const [pages,setpages]=useState(page)
  useEffect(() => {
    (async () => {
      let res = await getImgList()
      setimglist(res.data.data[0])
      setpage(res.data.data[1])
    })()
  }, [])
  // console.log(imglist);
  const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
    // setpage(current)
    // setpages(pageSize)
    // console.log(current, pageSize);

  };
  //点击头部x号按钮
  const text = '确认关闭?如果有内容变更，请先保存';

  const confirm = () => {
    message.info('关闭成功.');
    history.push("/pages/work")
  };
  //编辑or预览
  const [write, setwrite] = useState(false)
  const [writevalue, setwritevalue] = useState("编辑")
  //两栏观看
  const [twolan, settwolan] = useState(false)
  const [lanvalue, setlanvalue] = useState("两栏显示")
  //大纲
  const [outline, setoutline] = useState(false)
  const [outlinevalue, setoutlinevalue] = useState("大纲")


  // 上传
  const handleUpload = (e: newActicle) => {
    const { files } = e.target;
    let formDate = new FormData()
    formDate.append('file', files[0])
    request.defaults.headers.post['Authorization'] = `Bearer ${localStorage.getItem('token')}`
    request({
      url: "/api/file/upload?unique=0",
      method: 'post',
      data: formDate,
    }).then(async (res1) => {
      message.success('上传成功');
      await request.get(`https://2004a-oss.oss-cn-hangzhou.aliyuncs.com/${moment(new Date()).format('YYYY-MM-DD')}/${res1.data.data.originalname}`);
      let res = await getImgList()
      setimglist(res.data.data[0])
      setpage(res.data.data[1])
    })
  }
  return (
    <div className='newweb'>
      <header>
        <Popconfirm
          placement="rightTop"
          title={text}
          onConfirm={confirm}
          okText="确认"
          cancelText="取消"
        >
          <Button className='closebtn'>x</Button>
        </Popconfirm>
        <input type="text" onChange={(e) => {
          setvalue(e.target.value);
        }} />
        <div className='fbbox'>
          <Button type='primary' className='releasebtn' onClick={() => {
            value == "0" ? message.error("请输入页面名称") : showDrawer()
            // value=="0"?console.log(111):console.log(222);
            if (value1 !== "1") {
              // console.log(form1.getFieldsValue().url);
              onClose()
              request.post("https://bjwz.bwie.com/wipi/api/page", {
                content: conect,
                cover: form1.getFieldsValue().photobook,
                html: html,
                name: value,
                path: form1.getFieldsValue().url,
                status: "publish",
                toc: low,
                order:form1.getFieldsValue().sort
              }).then(res => {
                console.log(res);
                message.success("页面新建成功")
              })
            }
          }}>发布</Button>
          <Dropdown overlay={menu}>
            <a onClick={e => e.preventDefault()}>
              <Space>
                <svg className="icon-more" fill='#1890ff' viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2161" width="32" height="32"><path d="M288 512m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="2162"></path><path d="M512 512m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="2163"></path><path d="M736 512m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="2164"></path></svg>
              </Space>
            </a>
          </Dropdown>
        </div>

      </header>
      <main>
        <div className='fwbmain' style={{ border: '1px solid #ccc', zIndex: 100 }}>
          <div className='kheader'>
            <Toolbar
              editor={editor}
              defaultConfig={toolbarConfig}
              mode="default"
            />
            <p className='lan'>
              当前模式:<span onClick={() => {
                setwrite(!write)
                write ? setwritevalue("预览") : setwritevalue("编辑")
              }}>{writevalue}</span><span onClick={() => {
                settwolan(!twolan)
                twolan ? setlanvalue("退出两栏显示") : setlanvalue("两栏显示")
              }}>{lanvalue}</span>
              <span onClick={() => {
                setoutline(!outline)
              }}>{outlinevalue}</span>
            </p>
          </div>

          <div className='writebox'>
            <Editor
              defaultConfig={editorConfig}
              value={" "}
              onCreated={setEditor}
              onChange={editor => setHtml(editor.getHtml())}
              mode="default"
              style={{ flex: "1", height: "100%", overflowY: 'auto', float: "left" }}
            />
            {
              twolan ? <></> : <div className='htmlinner' dangerouslySetInnerHTML={{ __html: html }} />
            }
            {
              outline ? <></> : <div className='lowbox'id="tocBox" ref={tocBox} onClick={(e)=>{
                handleTocClick(e)
              }}></div>
            }
          </div>
        </div>
      </main >
      <Drawer width="500px" className='drawerbox' title="页面属性" placement="right" onClose={onClose} open={open}>
        {open ? message.warn("请输入页面路径") : ""}
        <Form
          form={form1}
          className='formbbox'
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="封面"
            name="photobook"
          >
            <Input />
          </Form.Item>
          <span className='webicon'><svg onClick={() => {
            showDrawerTwo()
            // console.log(123456);

          }} className="icon-web" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3039" width="32" height="32"><path d="M693.333333 298.666667a53.393333 53.393333 0 0 1-53.333333-53.333334V42.666667H181.333333a53.393333 53.393333 0 0 0-53.333333 53.333333v832a53.393333 53.393333 0 0 0 53.333333 53.333333h661.333334a53.393333 53.393333 0 0 0 53.333333-53.333333V298.666667z m-416-42.666667h213.333334a21.333333 21.333333 0 0 1 0 42.666667H277.333333a21.333333 21.333333 0 0 1 0-42.666667z m-21.333333 192a21.333333 21.333333 0 0 1 21.333333-21.333333h128a21.333333 21.333333 0 0 1 0 42.666666H277.333333a21.333333 21.333333 0 0 1-21.333333-21.333333z m430.326667 72.833333l-269.713334 269.72-114.14 16.306667 16.306667-114.14 269.72-269.713333a42.713333 42.713333 0 0 1 60.333333 0l37.493334 37.493333a42.713333 42.713333 0 0 1 0 60.333333zM682.666667 245.333333V55.42c1.066667 0.913333 2.12 1.86 3.126666 2.866667l194.586667 194.586666c1.006667 1.006667 1.953333 2.06 2.866667 3.126667H693.333333a10.666667 10.666667 0 0 1-10.666666-10.666667z" fill="#5C5C66" p-id="3040"></path></svg></span>

          <Form.Item
            label="路径"
            name="url"
          >
            <Input />
          </Form.Item>

          <Form.Item label="顺序" name="sort">
            <InputNumber />
          </Form.Item>

          <Form.Item >
            <Button onClick={(e) => {
              // console.log(value);
              // setvalue1()
              value1 == "1" ? message.warn("请输入路径") : onClose()
            }} type="primary" htmlType="submit" id='kjbtn'>
              确认
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
      <Drawer width={800} className='drawerboxtwo' title="文件选择" placement="right" onClose={onCloseTwo} open={openTwo}>
        <div className='drawerboxtwobox'>
          <p style={{ height: "50px", lineHeight: "50px", border: "1px #7aceff solid", backgroundColor: "#e6f7ff" }}>点击卡复制链接，点击图片查看大图</p>
          <Form
            form={form}
            className='formboxtwo'
            name="basic1"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            onFinish={onFinishTwo}
            onFinishFailed={onFinishFailedTwo}
            autoComplete="off"
          >
            <Form.Item
              label="文件名"
              name="filename"
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="文件类"
              name="filetype"
            >
              <Input />
            </Form.Item>

            <Form.Item className='pricturebtn' wrapperCol={{ offset: 8, span: 16 }}>
              <Button style={{ marginRight: "10px" }} type="primary" htmlType="submit" onClick={() => {
                // console.log(form.getFieldsValue());
                request.get("http://111.67.198.176:8103/api/file", {
                  params: {
                    originalname: form.getFieldsValue().filename
                  }
                }).then(res => {
                  console.log(res);
                  setimglist(res.data.data[0])
                  setpage(res.data.data[1])
                })
              }}>
                搜索
              </Button>
              <Button onClick={() => {
                (async () => {
                  let res = await getImgList()
                  setimglist(res.data.data[0])
                  setpage(res.data.data[1])
                })()
              }}>
                重置
              </Button>
            </Form.Item>
          </Form>
          <div className='prictruebox'>
            <p>
            <input style={{ marginLeft: "50px" }} id='file' type='file' onChange={handleUpload} />
              {/* <Button>上传文件</Button> */}
            </p>
            <div className='pictruedown'>
              <div className='ppp'>
                {
                  imglist && imglist.map((item: newActicle, index: number) => {
                    return <Card
                      hoverable
                      style={{ width: "20%", height: "200px", float: "left", margin: "10px 10px" }}
                      cover={<img alt="example" src={item.url} style={{ width: "100%", height: "150px" }} />}
                    >
                      <div onClick={()=>{
                       copy(item.originalname)
                       message.success("内容已复制到剪切板")
                      }}>
                      <Meta  description={item.originalname} style={{ width: "100%", height: "50px", marginTop: "-20px" }} />
                      </div>
                    </Card>
                  })
                }
              </div>
              <Pagination
                className='pppfy'
                total={page}
                showSizeChanger={true}
                showLessItems
                onShowSizeChange={onShowSizeChange}
                defaultPageSize={12}
                pageSizeOptions={[8, 12, 24, 36]}
                showTotal={total => `共有 ${page} 条`}
                onChange={async (current, pageSize) => {
                  // console.log(current, pageSize);
                  let res = await getImgListpage(current, pageSize)
                  setimglist(res.data.data[0])
                  setpage(res.data.data[1])
                }}
              />
            </div>
          </div>
        </div>
      </Drawer>
    </div >
  )
}

export default Newweb